package ball.sneaker;

import ball.sneaker.Server.MyHttpHandler;
import ball.sneaker.Server.MyHttpsConfigurator;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpsServer;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

/**
 *
 * @author Arthur
 */
public class SneakerServer {

    static final int DEFAULT_SERVER_PORT = 443;

    /**
     * logger
     */
    static private Logger logger;
    static{
        logger = Logger.getLogger("SystemLog");
    }

    static public void main(String args[]) {

        try {
            
            char[] passphrase = "MyPass".toCharArray();
            KeyStore ks = KeyStore.getInstance("JKS");
            ClassLoader loader = SneakerServer.class.getClassLoader();
            ks.load(loader.getResourceAsStream("sneaker.keystore"), passphrase);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, passphrase);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(ks);
            SSLContext ssl = SSLContext.getInstance("TLS");
            ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
            HttpsServer server = null;
           
            server = HttpsServer.create(new InetSocketAddress(DEFAULT_SERVER_PORT), 0);
            server.setHttpsConfigurator(new MyHttpsConfigurator(ssl));
            HttpContext ctx = server.createContext("/");
            ctx.setHandler(new MyHttpHandler());
            server.setExecutor(null);

            server.start();
            return;

        } catch (KeyManagementException ex) {
            Logger.getLogger(SneakerServer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnrecoverableKeyException ex) {
            Logger.getLogger(SneakerServer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SneakerServer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(SneakerServer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CertificateException ex) {
            Logger.getLogger(SneakerServer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (KeyStoreException ex) {
            Logger.getLogger(SneakerServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
